<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/employees/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="hExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employeeList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" width="150px" />
          <el-table-column label="头像" width="150px">
            <template v-slot="{row}">
              <imgHolder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}" name="error">
              {{ formatEmployee(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry">
            <template v-slot="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 放置分页组件 -->
          <!-- current-page:当前的页数 -->
          <!-- page-sizes：每页显示的条数选项 -->
          <!-- page-size：每页显示多少条 -->
          <!-- layout：布局 -->
          <el-pagination
            :current-page="pageParams.page"
            :page-sizes="[10,15,20]"
            :page-size="pageParams.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- <el-dialog v-if="showDialog" :visible.sync="showDialog">
      <empDialog @closeDialog="hClose" @success="hSuccess" />
    </el-dialog> -->
    <el-dialog ref="addEmployDialog" :visible.sync="showDialog" @closed="$refs.addEmployDialog.claerForm()">
      <empDialog @closeDialog="hClose" @success="hSuccess" />
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog ref="addEmployDialog" :visible.sync="showRoleDialog" title="分配角色">
      <assignRole ref="assingRole" :user-id="userId" @hclose="closeRoleDialog" />
    </el-dialog>
    <!-- <el-dialog v-if="showRoleDialog" ref="addEmployDialog" :visible.sync="showRoleDialog" title="分配角色">
      <assignRole :user-id="userId" @hclose="closeRoleDialog" />
    </el-dialog> -->
  </div>
</template>

<script>
import { getEmployees, deleteEmployee } from '@/api/employee'
import empConst from '@/constant/employees'
import empDialog from './empDialog.vue'
import dayjs from 'dayjs'
import assignRole from './assignRole.vue'
import AssignRole from './assignRole.vue'
// 枚举数据处理
/*  {
  1:'正式',
  2:'非正式'
} */
const obj = {}
empConst.hireType.forEach(item => {
  obj[item.id] = item.value
})

export default {
  components: {
    empDialog,
    AssignRole,
    assignRole
  },
  data() {
    return {
      pageParams: {
        page: 1,
        size: 10
      },
      total: 0,
      employeeList: [],
      showDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    // 获取员工信息
    async loadEmployees() {
      const res = await getEmployees(this.pageParams)
      // console.log(res)
      this.employeeList = res.data.rows
      this.total = res.data.total
    },
    // 格式化聘用形式
    formatEmployee(code) {
      return obj[code]
    },
    // 当每页显示的条数发生变化的时候
    handleSizeChange(val) {
      // console.log('条数' + val)
      this.pageParams.size = val
      this.loadEmployees()
    },
    // 当前页发生变化的时候
    handleCurrentChange(val) {
      // console.log(val)
      this.pageParams.page = val
      this.loadEmployees()
    },
    // 删除员工
    async delEmployee(id) {
      // console.log(id)
      // promise对象
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        type: 'warning'
      }).catch(e => e)
      // console.log(result)
      if (result !== 'confirm') return
      const res = await deleteEmployee(id).catch(e => this.$message.error(e.message))
      this.$message.success(res.message)
      // 解决删除的bug 当删除的数据是某一页的最后一条数据的时候，需要判断页数是否大于1，如果不是第一页，那么就让页数减一
      if (this.employeeList.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      // 重新获取数据
      this.loadEmployees()
    },
    // 关闭dialog
    hClose() {
      this.showDialog = false
    },
    // 刷新数据且关闭dialog
    hSuccess() {
      this.showDialog = false
      // 添加成功后将跳转至最后一页
      this.pageParams.page = Math.ceil(++this.total / this.pageParams.size)
      this.loadEmployees()
    },
    // 格式化日期
    formatDate(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // excel导出
    async hExport() {
      const excel = await import('@/vendor/Export2Excel').catch(e => e)
      // console.log(excel)
      // if (!excel.success) return

      // 发请求拿数据(所有)
      const res = await getEmployees({ page: 1, size: this.total })
      if (!res.success) return
      // console.log(res.data.rows)
      // 转格式
      const { header, data } = this.formatExcel(res.data.rows)

      // excel表示导入的模块对象
      // console.log(excel)
      excel.export_json_to_excel({
        header, // 表头 必填
        data, // 具体数据 必填
        filename: '员工信息表', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
      })
    },
    formatExcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      let data = []
      // 原数据：[{'username':'张三'，'workNumber':'9001'},{'username':'李四'，'workNumber':'9002'},...]
      // 目标：header ['username','workNumber'] => ['姓名','工号']
      // 先判断数据是否存在
      if (list.length === 0) return
      // 每项都转成中文的
      header = Object.keys(list[0]).map(item => mapInfo[item])
      // console.log(header)
      // 目标：data [{'张三','9001'}，{'李四','9002'}，...]
      // 遍历数组取value
      data = list.map(item => {
        // 聘用形式转换
        if (item.formOfEmployment === undefined) {
          item.formOfEmployment = '非正式'
        } else {
          item.formOfEmployment = obj[item.formOfEmployment]
        }
        return Object.values(item)
      })
      // console.log(data)
      return { header, data }
    },
    closeRoleDialog() {
      this.showRoleDialog = false
    },
    // 点击分配角色
    async hAssignRole(id) {
      this.showRoleDialog = true
      // 将用到父传子
      this.userId = id
      // 异步操作，如果不加nextTick则获取的是上一次的id
      await this.$nextTick()
      this.$refs.assingRole.loadUserRoles()
    }
  }

}
</script>
